<?php

namespace app\modules\permission\service;

use Yii;
use app\common\base\CommonService;
use app\modules\permission\models\Permission;
use app\helpers\DatetimeHelper;

class PermissionService extends CommonService
{
    function __construct()
    {
        // 对父类service(component)初始化，并指定model
        parent::init();
        $this->model = new Permission();
    }

    /** 
     * 授予权限
     */
    public function grant($userId, $deviceId, $right, $start_timestamp, $end_timestamp)
    {
        $info = $this->info([
            'condition' => [
                'userId' => $userId,
                'deviceId' => $deviceId,
            ],
            'orderby' => [
                'end_timestamp' => 3
            ]
        ],);

        //判断现在是否有权限
        if (!empty($info) && $info['end_timestamp'] > DatetimeHelper::msectime()) {
            return parent::error('ERROR_USER_ALREADY_HAS_JOB', '用户已有该设备的权限');
        }

        $this->model->userId = $userId;
        $this->model->deviceId = $deviceId;
        $this->model->right = $right;
        $this->model->start_timestamp = $start_timestamp;
        $this->model->end_timestamp = $end_timestamp;
        $this->model->save();

        return [
            'success' => 1
        ];
    }

    /**
     * 回收权限
     */
    public function revoke($userId, $deviceId)
    {
        $info = $this->info([
            'condition' => [
                'userId' => $userId,
                'deviceId' => $deviceId,
            ],
            'orderby' => [
                'end_timestamp' => 3
            ]
        ]);

        if (empty($info) || $info['end_timestamp'] < DatetimeHelper::msectime()) {
            return parent::error('ERROR_USER_HAS_NO_JOB', '用户没有该设备的权限');
        }

        // TODO: 以下这块，update不成功
        $now = DatetimeHelper::msectime();
        $res = $this->update([
            'end_timestamp' => $now
        ],[
            'userId' => $userId,
            'deviceId' => $deviceId,
        ]);

        return [
            'success' => 1,
        ];
    }
}
